package client_listen_update_files;

import java.io.File;

import dropbox.common.FileAction;
/**
 * implement the FileAction interface, with the way
 * its method should behave on client side
 * 
 * @author Yoav
 *
 */
public class ClientFileAction  implements FileAction {
	
	private final String savingLocation="C:\\temp\\download\\";
	
	@Override
	public void deleteFile(String filePath){
		File file=new File(savingLocation+filePath);
		//check if file is folder
		if (file.isDirectory()){
			//true
			deleteFolder(file);
		}
		else{
			//file
			file.delete();
		}
	}

	/**
	 * download a file from server according to given checkSum
	 */
	@Override
	public void createFile(String checkSum,String filePath){
		File file=new File(savingLocation+filePath);
		//check if exists
		if (file.exists() ){
			//delete
			file.delete();
		}
		//download file from server
		ServerCommManager.getCommManager().downloadFile(checkSum,file);
	}
	
	@Override
	public void createDir(String dirPath){
		File file=new File(savingLocation+dirPath);
		//check if file or not exists
		if (!file.isDirectory()){
			if (file.exists()){
				//file so delete
				file.delete();
			}
		}
		file.mkdirs();		
	}
	
	@Override
	public void rename(String oldPath, String newPath) {
		File fileOld=new File(savingLocation+oldPath);
		File fileNew=new File(savingLocation+newPath);
		fileOld.renameTo(fileNew);		
	}
	
	/*
	 * delete a folder and its sub folders recursively 
	 * @param folder given folder
	 */
	private void deleteFolder(File folder){
		File [] files=folder.listFiles();
		//go over files in folder
		for (File file : files){
			//check if dir
			if (file.isDirectory()){
				//recursive call
				deleteFolder(file);
			}
			else{
				//file
				file.delete();
			}
		}
		//delete folder
		folder.delete();		
	}
}
